package com.example.fw;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.ContactObject;

public class ContactHelper extends HelperWithWebDriverBase {

	public ContactHelper(AppManager manager) {
		super(manager);
	}

	public Set<ContactObject> getContacts() {
		manager.getNavigationHelper().goToContactCreation();
		WebElement table = findElements(By.tagName("maintable")).get(1);
		List<WebElement> checkboxes = table.findElements(By.name("selected[]"));
		Set<ContactObject> contacts = new HashSet<ContactObject>();
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			//
			title = title.substring("Select (".length(),
					title.length() - ")".length());
			//
			ContactObject contact = new ContactObject().setFName(title)
					.setLName(title).setId(checkbox.getAttribute("value"));
			contacts.add(contact);
		}
		return contacts;
	}

	public void createContact(ContactObject addContact) {
		manager.getNavigationHelper().goToContactCreation();
		fillContactForm(addContact);
		selectContactListBoxElement(addContact);
		submitFilledFormCreation();
		manager.getNavigationHelper().returnToContactListPage();
	}

	public void fillContactForm(ContactObject contactObject) {
		type(By.name("firstname"), contactObject.firstname);
		type(By.name("lastname"), contactObject.lastname);
		type(By.name("address"), contactObject.address);
		type(By.name("home"), contactObject.home);
		type(By.name("work"), contactObject.work);
		type(By.name("mobile"), contactObject.mobile);
		type(By.name("email"), contactObject.email);
		type(By.name("email2"), contactObject.email2);
		type(By.name("byear"), contactObject.byear);
		type(By.name("address2"), contactObject.address2);
		type(By.name("phone2"), contactObject.phone2);
	}

	public void selectContactListBoxElement(ContactObject contactObject) {
		typeselect(By.name("bday"), contactObject.bday);
		typeselect(By.name("bmonth"), contactObject.bmonth);
		typeselect(By.name("new_group"), contactObject.newgroup);
	}

	protected void submitContactMode() {
		click(By.name("update"));
	}

	public void deleteContact(String locatorvalue) {
		manager.getNavigationHelper().openMainPage();
		idContactLocator(locatorvalue);
		manager.getNavigationHelper().goToEditContactWindow();
		submitDeletContact();
		manager.getNavigationHelper().returnToContactListPage();
	}

	protected void submitDeletContact() {
		click(By.xpath("(//input[@name='update'])[2]"));
	}

	private void idContactLocator(String locatorvalue) {
		click(By.id(locatorvalue));
	}

	public void modeContact(String locatorvalue, ContactObject addContact) {
		manager.getNavigationHelper().openMainPage();
		idContactLocator(locatorvalue);
		manager.getNavigationHelper().goToEditContactWindow();
		fillContactForm(addContact);
		submitContactMode();
		manager.getNavigationHelper().returnToContactListPage();
	}

}